package com.example.util;

import com.example.base.domain.ZhiHuAnswer;
import com.example.base.domain.ZhiHuArticle;
import com.example.base.domain.ZhiHuFans;
import com.example.base.domain.ZhiHuTrend;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.lang.Nullable;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class HttpURLConnectionUtil {

    // 字符集
    private static String charset = "UTF-8";
    // 设置连接超时时间，单位毫秒
    private static int connectTimeout = 5000;
    // 设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的
    private static int connectionRequestTimeout = 5000;
    // 请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用
    private static int cocketTimeout = 60000;

    public static Map<String, String> auth(String cookie) {
        // 请求头
        Map<String, String> header = new HashMap<>();
        header.put("cookie", cookie);
        header.put("Content-type", "application/json");
        return header;
    }

    /**
     * Http get请求
     *
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static List<ZhiHuAnswer> doGetAnswer(String httpUrl, Map<String, String> header) {
        List<ZhiHuAnswer> zhiHuAnswerList = new ArrayList<>();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            HttpGet httpGet = new HttpGet(httpUrl);

            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setConnectTimeout(connectTimeout);
            builder.setConnectionRequestTimeout(connectionRequestTimeout);
            builder.setSocketTimeout(cocketTimeout);
            httpGet.setConfig(builder.build());

            for (String key : header.keySet()) {
                httpGet.addHeader(key, header.get(key));
            }

            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);

            for (CSVRecord record : records) {
                if (record.getRecordNumber() == 1) {
                    continue;
                }
                ZhiHuAnswer zhiHuAnswer = new ZhiHuAnswer();
                zhiHuAnswer.setTitle(record.get(0));
                zhiHuAnswer.setPublishTime(record.get(1));
                zhiHuAnswer.setLink(record.get(2));
                zhiHuAnswer.setPv(Integer.valueOf(record.get(3)));
                zhiHuAnswer.setPlay(Integer.valueOf(record.get(4)));
                zhiHuAnswer.setUpvote(Integer.valueOf(record.get(5)));
                zhiHuAnswer.setLike(Integer.valueOf(record.get(6)));
                zhiHuAnswer.setComment(Integer.valueOf(record.get(7)));
                zhiHuAnswer.setCollect(Integer.valueOf(record.get(8)));
                zhiHuAnswer.setShare(Integer.valueOf(record.get(9)));
                zhiHuAnswerList.add(zhiHuAnswer);
            }

            return zhiHuAnswerList;
        } catch (Exception e) {
            throw new RuntimeException("HttpClient查询失败" + e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {

            }
        }
    }

    /**
     * Http get请求
     *
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static List<ZhiHuArticle> doGetArticle(String httpUrl, Map<String, String> header) {
        List<ZhiHuArticle> zhiHuArticleList = new ArrayList<>();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            HttpGet httpGet = new HttpGet(httpUrl);

            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setConnectTimeout(connectTimeout);
            builder.setConnectionRequestTimeout(connectionRequestTimeout);
            builder.setSocketTimeout(cocketTimeout);
            httpGet.setConfig(builder.build());

            for (String key : header.keySet()) {
                httpGet.addHeader(key, header.get(key));
            }

            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);

            for (CSVRecord record : records) {
                if (record.getRecordNumber() == 1) {
                    continue;
                }
                ZhiHuArticle zhiHuArticle = new ZhiHuArticle();
                zhiHuArticle.setTitle(record.get(0));
                zhiHuArticle.setPublishTime(record.get(1));
                zhiHuArticle.setLink(record.get(2));
                zhiHuArticle.setPv(Integer.valueOf(record.get(3)));
                zhiHuArticle.setUpvote(Integer.valueOf(record.get(4)));
                zhiHuArticle.setLike(Integer.valueOf(record.get(5)));
                zhiHuArticle.setComment(Integer.valueOf(record.get(6)));
                zhiHuArticle.setCollect(Integer.valueOf(record.get(7)));
                zhiHuArticle.setShare(Integer.valueOf(record.get(8)));
                zhiHuArticleList.add(zhiHuArticle);
            }
            return zhiHuArticleList;
        } catch (Exception e) {
            throw new RuntimeException("HttpClient查询失败" + e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {

            }
        }
    }

    /**
     * Http post请求
     * @param httpUrl 连接
     * @param param 参数
     * @return
     */
    public static String doPost(String httpUrl, @Nullable String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //拼装参数
            if (null != param && param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            //设置权限
            //设置请求头等
            //开启连接
            //connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }


    /**
     * Http get请求
     *
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static List<ZhiHuTrend> doGetTrend(String httpUrl, Map<String, String> header) {
        List<ZhiHuTrend> zhiHuTrendList = new ArrayList<>();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            HttpGet httpGet = new HttpGet(httpUrl);

            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setConnectTimeout(connectTimeout);
            builder.setConnectionRequestTimeout(connectionRequestTimeout);
            builder.setSocketTimeout(cocketTimeout);
            httpGet.setConfig(builder.build());

            for (String key : header.keySet()) {
                httpGet.addHeader(key, header.get(key));
            }

            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);

            for (CSVRecord record : records) {
                if (record.getRecordNumber() == 1) {
                    continue;
                }
                ZhiHuTrend zhiHuTrend = new ZhiHuTrend();
                zhiHuTrend.setTime(record.get(0));
                zhiHuTrend.setPv(Integer.valueOf(record.get(1)));
                zhiHuTrend.setPlay(Integer.valueOf(record.get(2)));
                zhiHuTrend.setUpvote(Integer.valueOf(record.get(3)));
                zhiHuTrend.setLike(Integer.valueOf(record.get(4)));
                zhiHuTrend.setComment(Integer.valueOf(record.get(5)));
                zhiHuTrend.setCollect(Integer.valueOf(record.get(6)));
                zhiHuTrend.setShare(Integer.valueOf(record.get(7)));
                zhiHuTrendList.add(zhiHuTrend);
            }

            return zhiHuTrendList;
        } catch (Exception e) {
            throw new RuntimeException("HttpClient查询失败" + e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {

            }
        }
    }


    public static void main(String[] args) {
        String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
        System.out.println(message);
    }


    public static List<ZhiHuFans> doGetFans(String httpUrl, Map<String, String> header) {
        List<ZhiHuFans> zhiHuFansList = new ArrayList<>();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            HttpGet httpGet = new HttpGet(httpUrl);

            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setConnectTimeout(connectTimeout);
            builder.setConnectionRequestTimeout(connectionRequestTimeout);
            builder.setSocketTimeout(cocketTimeout);
            httpGet.setConfig(builder.build());

            for (String key : header.keySet()) {
                httpGet.addHeader(key, header.get(key));
            }

            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);

            for (CSVRecord record : records) {
                if (record.getRecordNumber() == 1) {
                    continue;
                }
                ZhiHuFans zhiHuFans = new ZhiHuFans();
                zhiHuFans.setTime(record.get(0));
                zhiHuFans.setTotal(Integer.valueOf(record.get(1)));
                zhiHuFans.setAdd(Integer.valueOf(record.get(2)));
                zhiHuFans.setReduce(Integer.valueOf(record.get(3)));
                zhiHuFans.setChange(Integer.valueOf(record.get(4)));
                zhiHuFans.setActive(Integer.valueOf(record.get(5)));
                zhiHuFans.setActiveRatio(record.get(6));
                zhiHuFansList.add(zhiHuFans);
            }

            return zhiHuFansList;
        } catch (Exception e) {
            throw new RuntimeException("HttpClient查询失败" + e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {

            }
        }
    }
}
